package groupon.com.bo.controller;

import groupon.com.util.BoNavigation;
import groupon.com.util.ViewConstants;
import groupon.com.validator.UserFormValidator;
import groupon.commom.model.UserEmail;
import groupon.common.util.AppUtil;
import groupon.user.bo.service.ManagerUserService;
import groupon.user.model.User;
import groupon.user.model.UserSearch;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/bo/users")
public class UserController extends BoNavigation{
	
	private final Logger log = Logger.getLogger(UserController.class);
	
	@SuppressWarnings("unused")
	@Autowired
	private ManagerUserService _managerUserService;
	
	@Autowired
	private UserFormValidator _userFormValidate ;
	
	private int pageItems = 5;
	

	 /**
     * For every request for this controller, this will 
     * create a person instance for the form.
     */
	@ModelAttribute
	public User newRequest(@RequestParam(required = false) Integer id){
		User user = new User();
		if(id != null){
			user = _managerUserService.findUser(id);	
		}
		return user;
	}
	
	@ModelAttribute
	public UserSearch newRequest(){
		return new UserSearch();
	}
	
	@RequestMapping(value = "/create-user", method = RequestMethod.GET)
	public String viewCreateUser(ModelMap model){
		User user = new User();
		model.addAttribute("user", user);
		model.addAttribute("subTab", "createUser");
		return ViewConstants.RETURN_CREATE_USER_PAGE;
	}
	
	@RequestMapping(value = "/create-user", method = RequestMethod.POST)
	public String submitCreateUser(User user, BindingResult result, Principal principal){
		_userFormValidate.validate(user, result);
		if(result.hasErrors()){
			return ViewConstants.RETURN_CREATE_USER_PAGE;
		}
		Date dateCreate = new Date();
		user.setCreatedDate(dateCreate);
		user.setModifiedDate(dateCreate);
		user.setRole("FO");
		user.setActive(false);
		user.setDeleted(false);
		user.setCreatedBy(principal.getName());
		String password = user.getPassword();
		user.setPassword(AppUtil.convertStringToMd5(password));
		_managerUserService.save(user);
		final String subject = "create user";
		UserEmail userEmail = new UserEmail(0, user.getEmail(), user.getUsername(), password, user.getFirstName(), user.getLastName());
		AppUtil.sendEmail(userEmail, subject);
		return ViewConstants.REDIRECT_MANAGER_PAGE;
	}
	
	//view page EditUser,return JSON
	@RequestMapping(value = "/edit-user", method = RequestMethod.GET)
	public @ResponseBody User viewEditUser(User user){
		System.out.println(">>>>>>>>>>>>>>>>>edit user : " + user.getUsername());
		return user;
	}
	
	//submit page EditUser
	@RequestMapping(value = "/edit-user" , method = RequestMethod.POST)
	public String submitEditUser(User user, ModelMap model){
		User newUser = _managerUserService.update(user);
		if(newUser == null){
			model.addAttribute("error", "Can't update this user,pls try it again");
		}
		return ViewConstants.REDIRECT_MANAGER_PAGE;
	}
	
	@RequestMapping(value = "/delete-user", method =RequestMethod.POST)
	public String submitDeleteUser(User user, ModelMap model){
		boolean flag = _managerUserService.delete(user.getId());
		if(!flag){
			model.addAttribute("error", "can't delete this user");
		}
		return ViewConstants.REDIRECT_MANAGER_PAGE;
	}
	
	//return JSON when view User
	@RequestMapping(value = "/view-user", method = RequestMethod.GET)
	public @ResponseBody User viewUser(User user){
		System.out.println(">>>>>>>>>>>>>>>>>view user" + user.getUsername());
		return user;
	}
	
	//for search-user
	@RequestMapping(value = "/search-user", method = RequestMethod.GET)
	public void viewSearchUser(ModelMap model, HttpServletRequest request){
		System.out.println("run get in here");
		if(request.getSession().getAttribute("userSearch") != null){
			UserSearch userSearch = (UserSearch)request.getSession().getAttribute("userSearch");
			model.addAttribute("userSearch", userSearch);
			List<User> users = new ArrayList<User>();
			if(request.getParameter("pager.offset") != null){
				users =  _managerUserService.searchUserInRange(userSearch, Integer.parseInt(request.getParameter("pager.offset")), pageItems);
			}else{
				users =  _managerUserService.searchUserInRange(userSearch, 0, pageItems);
			}
			
			model.addAttribute("users", users);
			model.addAttribute("size", request.getSession().getAttribute("totalSearchSize"));
			model.addAttribute("pageItems", pageItems);
		}else{
			model.addAttribute("pageItems", pageItems);
			model.addAttribute("size", 0);
		}
		model.addAttribute("subTab", "searchUser");
	}
	
	@RequestMapping(value = "/search-user", method = RequestMethod.POST)
	public String submitSearchUser(UserSearch userSearch, ModelMap model, HttpServletRequest request){
		List<User> listUserAll = _managerUserService.searchUserInRange(userSearch, 0, 0);
		request.getSession().setAttribute("userSearch", userSearch);
		request.getSession().setAttribute("totalSearchSize", listUserAll.size());
		List<User> users = new ArrayList<User>();
		if(request.getParameter("pager.offset") != null){
			users =  _managerUserService.searchUserInRange(userSearch, Integer.parseInt(request.getParameter("pager.offset")), pageItems);
		}else{
			users =  _managerUserService.searchUserInRange(userSearch, 0, pageItems);
		}
		if(request.getSession().getAttribute("totalSearchSize") == null){
			model.addAttribute("size", users.size());
		}else{
			model.addAttribute("size", request.getSession().getAttribute("totalSearchSize"));
		}
		model.addAttribute("users", users);
		model.addAttribute("pageItems", pageItems);
		return ViewConstants.RETURN_SEARCH_USER_PAGE;
	}
	
	@RequestMapping(value = "/active-user", method = RequestMethod.GET)
	public @ResponseBody String submitActiveUser(User user){
		user.setActive(true);
		User userUpdate = _managerUserService.update(user);
		return userUpdate.getUsername();
	}
	
	@RequestMapping(value = "/deactive-user", method = RequestMethod.GET)
	public @ResponseBody String submitDeActiveUser(User user){
		user.setActive(false);
		User userUpdate = _managerUserService.update(user);
		return userUpdate.getUsername();
	}
	
	@RequestMapping(value = "/change-pw", method = RequestMethod.GET)
	public void viewChangePw(){
	}
	
	@RequestMapping(value = "/change-pw", method = RequestMethod.POST)
	public String submitChangePw(){
		return ViewConstants.RETURN_SEARCH_USER_PAGE;
	}

	@Override
	public String getSubTab() {
		return "";
	}

	@Override
	public String getTab() {
		// TODO Auto-generated method stub
		return "user";
	}
	
	private List<User> getListUserInRange(List<User> listUsers, int offset, int pageItems){
		return listUsers.subList(offset, offset + pageItems);
	}

}
